<?php

namespace app\common\model;

use think\Db;
use think\helper\Time;
use think\Log;
use think\Model;

class AdvCount extends Model
{
    protected $auto = ['createtime'];
    protected $insert = ['createtime'];

    /**
     * 访问日志
     * @param $aid
     * @param $ip
     * @return int|string
     */
    public static function log($aid, $ip)
    {
        Db::startTrans();
        try {
            $AD = new AdvLists();
            $AD->where('id', $aid)->setInc('pv');
            // 检测该ip今日是否访问
            list($ts, $te) = Time::today();
            $isUV = self::where(['adv_lists_id' => $aid, 'ip' => $ip, 'createtime' => ['between', [$ts, $te]]])->find();
            if (!$isUV) {
                $AD->where('id', $aid)->setInc('uv');
            }
            $ret = (new AdvCount)->insert(['adv_lists_id' => $aid, 'ip' => $ip, 'createtime' => time()]);
            if (!$ret) {
                Log::error("写入访问记录失败:" . (new AdvCount)->getLastSql());
                Db::rollback();
                return null;
            }
            Db::commit();
            return $ret;
        } catch (\Exception $e) {
            Log::error("写入访问日志出错:" . $e->getMessage());
        }
        return null;
    }
}
